<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  winlossState: {
    type: Object,
    required: true,
    validator: (value) => {
      return 'win' in value && 'loss' in value;
    }
  }
});

const chartContainer = ref(null);
let chartInstance = null;

const calculateWinRate = () => {
  return ((props.winlossState.win / (props.winlossState.win + props.winlossState.loss)) * 100).toFixed(0) + '%';
};

const chartOption = {
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  series: [
    {
      name: '比赛结果',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      label: {
        formatter: calculateWinRate,
        show: true,
        position: 'center',
        color: 'rgb(83,131,232)',
        fontSize: 12,
        fontWeight: 'bold',
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 15,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        {
          value: props.winlossState.win,
          name: '胜利',
          itemStyle: { color: 'rgb(83,131,232)' },
        },
        {
          value: props.winlossState.loss,
          name: '失败',
          itemStyle: { color: 'rgb(232,64,87)' }
        }
      ]
    }
  ]
};

const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    chartInstance.setOption(chartOption);
    window.addEventListener('resize', resizeChart);
  }
};

const resizeChart = () => {
  chartInstance?.resize();
};

const updateChart = () => {
  if (chartInstance) {
    chartInstance.setOption({
      series: [{
        data: [
          { value: props.winlossState.win, name: '胜利' },
          { value: props.winlossState.loss, name: '失败' }
        ],
        label: {
          formatter: calculateWinRate
        }
      }]
    });
  }
};

onMounted(() => {
  initChart();
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart);
  chartInstance?.dispose();
});

// 监听数据变化
watch(() => props.winlossState, updateChart, { deep: true });
</script>

<template>
  <div ref="chartContainer" class="w-full h-full"></div>
</template>